# -*- coding: utf-8 -*-
import yaml
import jieba
import random
from qa_engine.user import User
from qa_engine.nlp import WordFilter
from qa_engine.handler import handler_class
from qa_engine.util import read_config_path


class QAEngine:
    """
    问答引擎
    """

    def __init__(self, path):
        """
        :param path: 配置文件路径, 格式yaml
        """

        with open(path, 'r', encoding='utf-8') as file:
            config = yaml.full_load(file)['qa-engine']
        # 单词过滤器
        self.config = config
        self._register_word_filters()
        # 过滤后如果发现原句已经为空则随机返回empty_response里的某个回应
        self.empty_response = config['empty-response']
        self.sorry_response = config['sorry-response']
        self._register_handlers()
        self._load_jieba_config()

    def response(self, user: User, question: str, position: str = ''):
        """
        问答主总控，基于aiml构建问题匹配器
        :param user: 问句对应的用户对象
        :param question:问句输入
        :param position:用户所在位置
        :return: str[]
        """
        for each_filter in self.word_filters:
            question, response = each_filter.filter(question)
            # 单词过滤后触发的立即返回事件
            if response:
                return [response]
            if len(question) == 0:
                # 如果为空则直接随机返回empty-response中的一个
                return [random.choice(self.empty_response)]
        for each_handler in self.handlers:
            response = each_handler.handle(question, user, position)
            if response:
                return response
        # 随机返回不能处理的回答
        return [random.choice(self.sorry_response)]

    def _load_jieba_config(self):
        """
        加载jieba模块的配置
        :return:
        """
        for each in self.config['jieba']['userdict']:
            jieba.load_userdict(read_config_path(each))

    def _register_word_filters(self):
        """
        读取单词过滤器的格式
        :return: 过滤器列表
        """
        self.word_filters = []
        for each_filter in self.config['word-filter']:
            # 替换字典
            sub_dict = {}
            if not each_filter['repl']:
                each_filter['repl'] = ''
            for each_word in each_filter['word']:
                sub_dict[each_word] = each_filter['repl']
            # 注册单词过滤器
            if 'response' in each_filter.keys():
                # 如果有配置响应字符串
                self.word_filters.append(
                    WordFilter(sub_dict, each_filter['response'])
                )
            else:
                self.word_filters.append(WordFilter(sub_dict))
        return self.word_filters

    def _register_handlers(self):
        """
        读取问句处理程序配置
        :return:
        """
        # 问题处理器, 顺序尝试, 如果返回有效应答, 直接返回之
        self.handlers = []
        for each_handler in self.config['handler']:
            self.handlers.append(
                handler_class[each_handler['class']](each_handler['config'])
            )
